package cn.edu.ctbu.demo1.api;

import cn.edu.ctbu.demo1.core.RUtil;
import cn.edu.ctbu.demo1.domain.Student;
import cn.edu.ctbu.demo1.service.StudentService;
import cn.edu.ctbu.demo1.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/api/login")
public class LoginApiController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/student")
    public R student(String name , String classname) throws Exception{
        Student byNameLikeAndClassname = studentService.findByNameLikeAndClassname(name, classname);
        return RUtil.success(byNameLikeAndClassname);
    }

    @GetMapping("/user")
    public int user(HttpServletRequest httprequest, String username, String password){
        //判断用户名和密码是否存在
        List<Student> students = studentService.findByNameLikeAndPassword(username,password);

        if(students.size()>0){
            //人如果存在，写入Session
            HttpSession session = httprequest.getSession();
            session.setAttribute("userid",students.get(0).getId());

            session.setAttribute("user",students.get(0));

            return 1;//成功
        }else {
            return -1;//不存在用户
        }

    }

    @GetMapping("/nginxlogin")
    public int nginxlogin(HttpServletRequest httpServletRequest){
        HttpSession session = httpServletRequest.getSession();

        if(session.getAttribute("userid") == null){
            //没有登录，请先去登录
            return -1;
        }else {
            return 1;
        }
    }
}
